package cn.com.surker.wechat;

import cn.com.surker.common.HttpRequestHelper;
import cn.com.surker.redis.RedisUtils;
import cn.com.surker.spring.SpringContextHolder;
import cn.com.surker.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author lucky
 * @create 2022年07月25 10:15
 * @desc
 */
public class WechatMineGroupApi {

    private static Logger log = LoggerFactory.getLogger(WechatMineGroupApi.class);

    /**企业微信的**/
    public static String corpID = "wwd85ae41a2d988bc8";
    /**企业微信密匙**/
    public static String corpSecret = "nNZ5AsFyab4BvXWuda4BKa1b3fiH79OhXi_TbSQQoQY";
    /**应用ID**/
    public static String agentId = "1000016";
    /**缓存键**/
    public static String accessTokenKey = "mine_cloud_access_token";
    /**缓存时间**/
    public static Long sessionExpired = 7200L;

    public static void main(String[] args){
        String token = "abRGH7iQQqClv9Q0Yehz6-O1TFoJNcWeql2Exf3G6i8wXiePUQwxcpsuu--aUBCzeE6lQZg4QCDeljUek96WlvV0LavJSegMsq1d4BN4faiCofkUcYnpfvbBwzvBzoVTfFwwCbj3lgfecZ3PtDOJPwYMFzMDm66almHPx0OTCzA1H0ZPtWSq6os65gIXZRlDrx__OoQfXoI1uZJzIcTQYA";

        /**请求参数**/
        JSONObject textJson = new JSONObject();
        JSONObject json = new JSONObject();
        textJson.put("title", "测试卡片");
        textJson.put("description", "啊啊啊啊啊");
        textJson.put("url", "http://mine.chixugroup.com/cloud/purchase/material?code=111111&dsss=2222");

        json.put("touser", "1lgq996");
        json.put("msgtype", "textcard");
        json.put("agentid", agentId);
        json.put("textcard", textJson);
        try {
            String access_token = token;
            /**消息请求地址**/
            String postUrl = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + access_token;
            /**请求结果**/
            String result = HttpRequestHelper.senPostJson(postUrl, json.toJSONString());
            JSONObject obj = JSONObject.parseObject(result);
            Integer code = obj.getInteger("errcode");
            System.out.println(obj);
        } catch (Exception e) {
            log.error("获取企业微信用户信息失败：" + e.getMessage(), e);
        }

    }

    /**
     * 企业微信推送信息
     * @param touser 接收用户
     * @param msgType 消息类型
     * @param title 标题
     * @param description 描述
     * @param url 跳转地址
     * @return
     */
    public static Boolean sendTextCardMessage(String touser, String msgType, String title, String description, String url) {
        RedisUtils redisUtils = SpringContextHolder.getBean("redisUtils");
        if(!redisUtils.exists(accessTokenKey))
            loadGroupToken();
        /**请求参数**/
        JSONObject textJson = new JSONObject();
        JSONObject json = new JSONObject();
        textJson.put("title", title);
        textJson.put("description", description);
        textJson.put("url", url);

        json.put("touser", touser);
        json.put("msgtype", msgType);
        json.put("agentid", agentId);
        json.put("textcard", textJson);
        try {
            String access_token = StringUtils.convertString(redisUtils.get(accessTokenKey));
            /**消息请求地址**/
            String postUrl = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + access_token;
            /**请求结果**/
            String result = HttpRequestHelper.senPostJson(postUrl, json.toJSONString());
            JSONObject obj = JSONObject.parseObject(result);
            Integer code = obj.getInteger("errcode");
            if(code == 0){
                return true;
            } else if (code == 42001 || code == 40014){//token失效
                log.error("企业微信用户验证token失效，重新获取token");
                redisUtils.remove(accessTokenKey);
                loadGroupToken();
                return sendTextCardMessage(touser, msgType, title, description, url);
            } else {
                log.error("企业微信推送信息失败：" + result);
                return null;
            }
        } catch (Exception e) {
            log.error("获取企业微信用户信息失败：" + e.getMessage(), e);
            return false;
        }
    }

    /**
     *  获取企业微信的token
     */
    public static String getGroupToken() {
        RedisUtils redisUtils = SpringContextHolder.getBean("redisUtils");
        if (redisUtils.exists(accessTokenKey)) {
            return StringUtils.convertString(redisUtils.get(accessTokenKey));
        }
        String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + corpID + "&corpsecret=" + corpSecret;
        try {
            String res = HttpRequestHelper.get(url);
            JSONObject obj = JSONObject.parseObject(res);
            if("ok".equals(obj.getString("errmsg"))){
                log.info("access_token=" + obj.getString("access_token"));
                redisUtils.set(accessTokenKey, obj.getString("access_token"), sessionExpired);
                return obj.getString("access_token");
            } else {
                log.error("获取企业微信API token失败：" + res);
                return "";
            }
        } catch (Exception e) {
            log.error("获取企业微信API token失败：" + e.getMessage(), e);
            return "";
        }
    }

    /**
     * 根据CODE获取用户信息
     * @param code
     * @return
     */
    public static String getUserId(String code){
        RedisUtils redisUtils = SpringContextHolder.getBean("redisUtils");
        if(!redisUtils.exists(accessTokenKey))
            loadGroupToken();

        Map<String, String> params = new HashMap<String, String>();
        params.put("code", code);
        String access_token = StringUtils.convertString(redisUtils.get(accessTokenKey));
        String url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=" + access_token + "&code=" + code;
        try {
            log.error("根据CODE获取用户信息url:{},code:{},access_token:{}", url, code, access_token);
            String res = HttpRequestHelper.get(url);
            JSONObject obj = JSONObject.parseObject(res);
            log.error("根据CODE获取用户信息object:{}", res);
            Integer c = obj.getInteger("errcode");
            if(c == 0){
                return obj.getString("UserId");
            } else if (c == 42001 ){//token失效
                log.error("企业微信用户验证token失效，重新获取token");
                loadGroupToken();
                return getUserId(code);
            } else if(c == 40029){
                log.error("企业微信用户验证code失效");
                return null;
            } else if(c == 40014){
                log.error("企业微信用户验证token失效，重新获取token");
                loadGroupToken();
                return getUserId(code);
            } else {
                log.error("企业微信用户验证失败：" + res);
                return null;
            }
        } catch (Exception e) {
            log.error("获取企业微信用户信息失败：" + e.getMessage(), e);
            return null;
        }

    }

    /**
     *  加载企业微信的token
     */
    public static void loadGroupToken() {
        RedisUtils redisUtils = SpringContextHolder.getBean("redisUtils");
        if (redisUtils.exists(accessTokenKey))
            return;

        String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + corpID + "&corpsecret=" + corpSecret;

        try {
            String res = HttpRequestHelper.get(url);
            JSONObject obj = JSONObject.parseObject(res);
            log.error("企业微信获取access_token:{},token_url:{}", res, url);
            if("ok".equals(obj.getString("errmsg"))){
                log.info("验证后的access_token:{}", obj.getString("access_token"));
                redisUtils.set(accessTokenKey, obj.getString("access_token"), sessionExpired);
            } else {
                log.error("获取企业微信API token失败：" + res);
            }
        } catch (Exception e) {
            log.error("获取企业微信API token失败：" + e.getMessage(), e);
        }
    }
}
